package com.longshihan.carservice.service.user;

import com.longshihan.carservice.constant.ErrorConstant;
import com.longshihan.carservice.dao.UserDao;
import com.longshihan.carservice.exception.BusinessException;
import com.longshihan.carservice.model.UserDomain;
import com.longshihan.carservice.utils.TaleUtils;
import com.longshihan.carservice.utils.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;//这里会报错，但是并不会影响

    @Override
    public int updateUserInfo(UserDomain user) {
        if (null == user.getUid())
            throw BusinessException.withErrorCode("用户编号不可能为空");
        return userDao.updateUserInfo(user);
    }

    @Override
    public UserDomain getUserInfoById(Integer uId) {
        return userDao.getUserInfoById(uId);
    }

    @Override
    public UserDomain getUserInfoByWeChatId(String wechatId) {
        return userDao.getUserInfoByWeChatId(wechatId);
    }

    @Override
    public UserDomain getUserInfoByCond(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password))
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_IS_EMPTY);

        String pwd = TaleUtils.MD5encode(username + password);
        UserDomain user = userDao.getUserInfoByCond(username, pwd);
        if (null == user)
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_ERROR);

        return user;
    }

    @Override
    public void registerUserDomain(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password))
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_IS_EMPTY);
        String pwd = TaleUtils.MD5encode(username + password);
         userDao.registerUserDomain(username, pwd);
    }

    @Override
    public int registerUserDomainByWechat(String wechatId,String name) {
        if (StringUtils.isBlank(wechatId))
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_IS_EMPTY);
        String uid= UUID.UU64();
        int user = userDao.registerUserDomainByWechat(uid,wechatId, name);
        if ( user!=1)
            throw BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_ERROR);

        return user;
    }
}
